package view.swing;

import static util.Strings.STR_SCORE_PANEL;

import java.awt.BorderLayout;
import java.awt.Font;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.JTableHeader;

import model.events.PlayerEvent;
import model.events.ScoreEvent;
import model.swing.PlayersTableModel;
import view.IPlayersView;

public class PlayersView implements IPlayersView {

	private JPanel playersPanel = new JPanel();

	public PlayersView() {
		super();
	}

	public PlayersView(PlayersTableModel ptm) {
		this();
		buildView(ptm);
	}

	private void buildView(PlayersTableModel ptm) {

		BoxLayout layout = new BoxLayout(playersPanel, BoxLayout.Y_AXIS);

		playersPanel.setLayout(layout);
		
		JTable tableau = new JTable(ptm);
		tableau.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		tableau.setEnabled(false);
		CenterTableCellRenderer cellRenderer = new CenterTableCellRenderer();
		for (int i = 0; i < tableau.getColumnCount(); i++) {
			tableau.setDefaultRenderer(tableau.getColumnClass(i), cellRenderer);
		}
		JLabel titre = new JLabel(STR_SCORE_PANEL);
		titre.setFont(titre.getFont().deriveFont(Font.BOLD));
		titre.setAlignmentX((float) 0.5);
		titre.setHorizontalAlignment(SwingConstants.CENTER);

		playersPanel.add(titre);

		JPanel panelTableau = new JPanel();
		BorderLayout bl = new BorderLayout();
		panelTableau.setLayout(bl);
		
		JTableHeader header = tableau.getTableHeader();
		header.setAlignmentX(JTableHeader.CENTER_ALIGNMENT);
		header.setAlignmentY(JTableHeader.CENTER_ALIGNMENT);
		header.setDefaultRenderer(new CenterTableCellRenderer());
		header.setReorderingAllowed(false);
		header.setResizingAllowed(false);
		
		panelTableau.add(header, BorderLayout.PAGE_START);
		panelTableau.add(tableau, BorderLayout.CENTER);

		playersPanel.add(panelTableau);
	}

	public JPanel getPanel() {
		return this.playersPanel;
	}

	/* (non-Javadoc)
     * @see view.swing.IPlayersView#scoreChanged(model.events.ScoreEvent)
     */
	@Override
	public void scoreChanged(ScoreEvent event) {
		playersPanel.updateUI();
	}

	/* (non-Javadoc)
     * @see view.swing.IPlayersView#playerChanged(model.events.PlayerEvent)
     */
	@Override
	public void playerChanged(PlayerEvent event) {
		playersPanel.updateUI();
	}

}
